<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:c="livcos.org/ns/cosmos"
  xmlns:job="livcos.org/ns/process/job"
  xmlns:u="livcos.org/ns/cosmos/update"
  xmlns:da="livcos.org/ns/cosmos/data-access"
  xmlns:pm="livcos.org/ns/tmp/pm"
  exclude-result-prefixes="c job u pm">
  
  <xsl:variable name="projs" select="document('Projects.view')/*/*"/>
  <xsl:variable name="result_container_objId" select="'/livcos.org/LivCos/data/tmp'"/>
  
  <xsl:template match="/">
    <u:context ref="{$result_container_objId}" scope="meta">
      <xsl:apply-templates select="$projs" mode="root"/>
    </u:context>
    <job:feed stream="response" base="job" content-type="text/html; charset=UTF-8">
      <p>
        The projects have been generated to '<xsl:value-of select="$result_container_objId"/>'.
      </p>
    </job:feed>
  </xsl:template>
  
  <xsl:template match="pm:project" mode="root">
    <u:insert select="da:folder" create-path="yes">
      <xsl:apply-templates select="."/>
    </u:insert>
  </xsl:template>
  
  <xsl:template match="pm:project">
    <xsl:element name="{pm:label}" namespace="livcos.org/ns/cosmos">
      <xsl:apply-templates select="pm:project"/>
      <c:Intro>
        <document xmlns="livcos.org/ns/doc">
          <head>
            <title>Intro</title>
          </head>
          <body>
            <chapter id="chapter_1">
              <title>Summary</title>
              <paragraph id="paragraph_1">
                <xsl:value-of select="pm:description"/>
                <xsl:if test="normalize-space(pm:description) = ''">...</xsl:if>
              </paragraph>
            </chapter>
          </body>
        </document>
      </c:Intro>
      <c:project>
        <project xmlns="livcos.org/ns/pm" created="{@created}" modified="{@modified}">
          <xsl:copy-of select="pm:title"/>
          <xsl:copy-of select="pm:description"/>
          <xsl:apply-templates select="pm:project" mode="dependent"/>
        </project>
      </c:project>
      <c:schedule>
        <task xmlns="livcos.org/ns/pm" priority="@priority" progress="@progress">
          <xsl:copy-of select="pm:schedule | pm:task"/>
        </task>
      </c:schedule>
      <c:issues>
        <issues xmlns="livcos.org/ns/pm">
          <xsl:copy-of select="pm:feature"/>
          <xsl:copy-of select="pm:bug"/>
        </issues>
      </c:issues>
    </xsl:element>
  </xsl:template>
  
  <xsl:template match="pm:project" mode="dependent">
    <xsl:variable name="path" select="if (count(ancestor::pm:project) > 1) then '../' else ''"/>
    <project xmlns="livcos.org/ns/pm" ref="{$path}{pm:label}"/>
  </xsl:template>
  
</xsl:stylesheet>
